#include "tuya_iot_kit.h"


iot_data_t iot_data;
tuya_event_msg_t event_msg;
tuya_iot_client_t *m_client = nullptr;
tuya_iot_client_t client;

Tuya_IoT_Kit_Qthread::Tuya_IoT_Kit_Qthread(QObject *parent)
{
    (void)parent;

    iot_data.handle_flag = false;

    memset(&event_msg,0x00,sizeof(tuya_event_msg_t));

}

Tuya_IoT_Kit_Qthread::~Tuya_IoT_Kit_Qthread()
{

}


void Tuya_IoT_Kit_Qthread::run()
{
    tuya_iot_kit_init();
    m_client = &client;

    //memcpy(&m_client, &client, sizeof(tuya_iot_client_t));

    while(1)
    {
        tuya_iot_yield(&client);
    }
}


void Tuya_IoT_Kit_Qthread::tuya_iot_report_bool_value(char *dp, bool flag)
{
    QByteArray ba;
    QString json_str;

    json_str = "\""+QString(QLatin1String(dp))+"\""+':';

    if(flag)json_str += "true";
    else json_str += "false";

    json_str.prepend("{");
    json_str.append("}");

    ba = json_str.toLatin1();

    //qDebug() << "json_str = " << json_str;
    //qDebug().noquote() << "json_str = " << json_str;
    //printf(">>> json_str ba = %s",ba.data());

    tuya_iot_dp_report_json(m_client, ba.data());
}

void Tuya_IoT_Kit_Qthread::tuya_iot_report_int_value(char *dp, int value)
{
    QByteArray ba;
    QString json_str;

    json_str = "\""+QString(QLatin1String(dp))+"\""+':'+QString::number(value,10);

    json_str.prepend("{");
    json_str.append("}");

    ba = json_str.toLatin1();

    //qDebug() << "json_str = " << json_str;
    //qDebug().noquote() << "json_str = " << json_str;
    //printf(">>> json_str ba = %s",ba.data());

    tuya_iot_dp_report_json(m_client, ba.data());

    //const char int_value[] = {"{\"103\":56}"};
    //tuya_iot_dp_report_json(m_client, int_value);
}

void Tuya_IoT_Kit_Qthread::tuya_iot_report_string_value(char *dp, char *str)
{
    QByteArray ba;
    QString json_str;
    QString temp_str;

    json_str = "\""+QString(QLatin1String(dp))+"\""+":";
    temp_str = "\""+QString(QLatin1String(str))+"\"";

    json_str += temp_str;

    json_str.prepend("{");
    json_str.append("}");

    ba = json_str.toLatin1();

    //qDebug() << "json_str = " << json_str;
    //qDebug().noquote() << "json_str = " << json_str;
    //printf(">>> json_str ba = %s",ba.data());

    tuya_iot_dp_report_json(m_client, ba.data());
}

void Tuya_IoT_Kit_Qthread::tuya_iot_report_enum_value(char *dp, int enum_value)
{
    QByteArray ba;
    QString json_str;

    json_str = "\""+QString(QLatin1String(dp))+"\""+':'+QString::number(enum_value,10);

    json_str.prepend("{");
    json_str.append("}");

    ba = json_str.toLatin1();

    //qDebug() << "json_str = " << json_str;
    //qDebug().noquote() << "json_str = " << json_str;
    //printf(">>> json_str ba = %s",ba.data());

    tuya_iot_dp_report_json(m_client, ba.data());
}

void Tuya_IoT_Kit_Qthread::tuya_iot_report_raw_value(char *dp, char *p_buff)
{
    QByteArray ba;
    QString json_str;
    QString temp_str;

    json_str = "\""+QString(QLatin1String(dp))+"\""+":";
    temp_str = "\""+QString(QLatin1String(p_buff))+"\"";

    json_str += temp_str;

    json_str.prepend("{");
    json_str.append("}");

    ba = json_str.toLatin1();

    //qDebug() << "json_str = " << json_str;
    //qDebug().noquote() << "json_str = " << json_str;
    //printf(">>> json_str ba = %s",ba.data());

    tuya_iot_dp_report_json(m_client, ba.data());
}

/* DP 数据点解析函数
#define DP_PH_VALUE             "101"
#define DP_BRIGHT_STATE         "102"
#define DP_HUMIDITY             "103"
#define DP_TEMPERATURE          "104"
#define DP_BRIGHT_VALUE         "105"
#define DP_TEMP_UNIT_CONVERT    "106"
#define DP_BATTERY_STATE        "107"
#define DP_BATTERY_PERCENTAGE   "108"
#define DP_MOTOR_CTRL           "109"
#define DP_LIGHT_CTRL           "110"

*/


int Tuya_IoT_Kit_Qthread::dp_motor_ctrl_process(cJSON *p_obj)
{
    int ret = 0;
    if (cJSON_IsTrue(p_obj))
    {
        qDebug() << ">>> 109 on >>>";
        iot_data.motor_ctrl = true;
    }
    else if (cJSON_IsFalse(p_obj))
    {
        qDebug() << ">>> 109 off >>>";
        iot_data.motor_ctrl = false;
    }

    iot_data.handle_flag |= FLAG_2;
    return ret;
}

int Tuya_IoT_Kit_Qthread::dp_light_ctrl_process(cJSON *p_obj)
{
    int ret = 0;

    if (cJSON_IsTrue(p_obj))
    {
        qDebug() << ">>> 110 on >>>";
        iot_data.light_ctrl = true;
    }
    else if (cJSON_IsFalse(p_obj))
    {
        qDebug() << ">>> 110 off >>>";
        iot_data.light_ctrl = false;
    }

    iot_data.handle_flag |= FLAG_3;
    return ret;
}

void Tuya_IoT_Kit_Qthread::tuya_iot_dp_download(tuya_iot_client_t* client, const char* json_dps)
{
    qDebug() << ">>> tuya_iot_dp_download >>> " << json_dps;
    cJSON* dps = NULL;
    cJSON* switch_obj = NULL;
    int dp_idx = 0;

    char dp_list[10][4] = {DP_PH_VALUE, DP_BRIGHT_STATE, DP_HUMIDITY, DP_TEMPERATURE, \
                        DP_BRIGHT_VALUE, DP_TEMP_UNIT_CONVERT, DP_BATTERY_STATE, \
                        DP_BATTERY_PERCENTAGE, DP_MOTOR_CTRL, DP_LIGHT_CTRL};

    dps = cJSON_Parse(json_dps);
    if (dps == NULL) {
        qDebug() << "JSON parsing error, exit!";
        return;
    }

    for(int i = 0;i < 10;i++)
    {
        switch_obj = cJSON_GetObjectItem(dps, &dp_list[i][0]);
        if(switch_obj != NULL){dp_idx = i;break;}
    }

    //qDebug() << switch_obj << "dp_ipx = " << dp_idx;

    switch (dp_idx)
    {
        case 8://DP_MOTOR_CTRL
        {
            dp_motor_ctrl_process(switch_obj);
        }break;

        case 9://DP_LIGHT_CTRL
        {
            dp_light_ctrl_process(switch_obj);
        }break;

        default:break;
    };

    cJSON_Delete(dps);

    tuya_iot_dp_report_json(client, json_dps);    //回复云平台，同步数据处理的状态

}

void Tuya_IoT_Kit_Qthread::user_event_handler_on(tuya_iot_client_t* client, tuya_event_msg_t* event)
{   
    qDebug() << ">>> event->type = >>> " << event->type;

    switch(event->id)
    {
        case TUYA_EVENT_BIND_START:break;

        case TUYA_EVENT_MQTT_CONNECTED:
        {
            event_msg.id = event->id;
            iot_data.cloud_state = CLOUD_CONNECT;
            iot_data.handle_flag |= FLAG_1;
        }break;

        case TUYA_EVENT_MQTT_DISCONNECT:
        {
            event_msg.id = event->id;
            iot_data.cloud_state = CLOUD_DISCONNECT;
            iot_data.handle_flag |= FLAG_0;
        }break;

        case TUYA_EVENT_DP_RECEIVE:
        {
            event_msg.id = event->id;
            tuya_iot_dp_download(client, (const char*)event->value.asString);

        }break;

        default:break;
    }
}

int Tuya_IoT_Kit_Qthread::tuya_iot_kit_init(void)
{
    int ret = OPRT_OK;

    tuya_iot_config_t iot_config = {
        .productkey = TUYA_PRODUCT_KEY,
        .uuid = TUYA_DEVICE_UUID,
        .authkey = TUYA_DEVICE_AUTHKEY,
        .software_ver = SOFTWARE_VERS,
        .modules = nullptr,
        .skill_param = nullptr,
        .storage_namespace = nullptr,
        .firmware_key = nullptr,
        .event_handler = user_event_handler_on,
    };

    //初始化涂鸦 IoT Device
    ret = tuya_iot_init(&client, &iot_config);

    assert(ret == OPRT_OK);

    //开始涂鸦 IoT 任务
    tuya_iot_start(&client);

    return ret;
}
